package com.blacktech.dbu.core.config;

import com.blacktech.dbu.core.dict.ColumnType;
import com.blacktech.dbu.core.dict.DatabaseDialect;
import com.blacktech.dbu.core.dict.DbTypeMappingConfig;
import jakarta.annotation.PostConstruct;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;

import java.util.HashMap;
import java.util.Map;

/**
 * DDL类型映射配置类
 * 用于从独立的YAML配置文件加载数据库类型映射
 *
 * @author yanyunsong
 */
@Configuration
@PropertySource(value = "classpath:dbu-ddl.yml", factory = YamlPropertySourceFactory.class)
@ConfigurationProperties(prefix = "dbu.ddl")
public class DDLTypeMappingConfig {
    
    /**
     * 类型映射配置
     * 格式: Map<ColumnType, Map<DatabaseDialect, String>>
     */
    private Map<String, Map<String, String>> typeMappings = new HashMap<>();
    
    @PostConstruct
    public void init() {
        // 将配置文件中的映射关系加载到全局配置中
        for (Map.Entry<String, Map<String, String>> entry : typeMappings.entrySet()) {
            String columnTypeStr = entry.getKey();
            Map<String, String> dialectMappings = entry.getValue();
            
            try {
                ColumnType columnType = ColumnType.valueOf(columnTypeStr.toUpperCase());
                
                for (Map.Entry<String, String> dialectEntry : dialectMappings.entrySet()) {
                    String dialectStr = dialectEntry.getKey();
                    String dbType = dialectEntry.getValue();
                    
                    try {
                        DatabaseDialect dialect = DatabaseDialect.valueOf(dialectStr);
                        DbTypeMappingConfig.setTypeMapping(columnType, dialect, dbType);
                    } catch (IllegalArgumentException e) {
                        // 忽略无法识别的数据库方言
                    }
                }
            } catch (IllegalArgumentException e) {
                // 忽略无法识别的字段类型
            }
        }
    }
    
    public Map<String, Map<String, String>> getTypeMappings() {
        return typeMappings;
    }
    
    public void setTypeMappings(Map<String, Map<String, String>> typeMappings) {
        this.typeMappings = typeMappings;
    }
}